package com.pfzy.lib.sdk.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;

import androidx.annotation.NonNull;

import com.pfzy.lib.sdk.log.UXLog;
import com.pfzy.lib.sdk.utils.zip.ZipChannelUtils;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class DeviceUtil {
    private static final String FILE_NAME = ".device2";
    public static final String IMEI_1 = "device_imei_1";
    public static final String IMEI_2 = "device_imei_2";
    public static final String KEY_CHANNEL = "KEY_CHANNEL";
    public static final int Q = 29;
    public static final String TAG = "DeviceUtil";
    private static String imei;
    private static boolean isInited = false;

    public static void init(Context context) {
        if (!isInited) {
            isInited = true;
            Context appContext = context.getApplicationContext();
            Common.setContext(appContext);
            ActivityStateMonitor.init();
        }
    }

    public static String getChannelNameFromApk() {
        ApplicationInfo appinfo = Common.getContext().getApplicationInfo();
        String sourceDir = appinfo.sourceDir;
        File apkFile = new File(sourceDir);
        String channelFileName = ZipChannelUtils.getChannelFileName(apkFile);
        if (TextUtils.isEmpty(channelFileName)) {
            ZipFile zipfile = null;

            try {
                zipfile = new ZipFile(sourceDir);
                Enumeration<?> entries = zipfile.entries();

                while (entries.hasMoreElements()) {
                    ZipEntry entry = (ZipEntry) entries.nextElement();
                    String entryName = entry.getName();
                    if (entryName.contains("caocaozhuanche_channel_")) {
                        channelFileName = entryName;
                        break;
                    }
                }

                if (zipfile != null) {
                    zipfile.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Throwable th) {
                throw th;
            }
        }
        return channelFileName;
    }

    public static int getWidth() {
        DisplayMetrics dm = Common.getContext().getResources().getDisplayMetrics();
        return dm.widthPixels;
    }

    public static int getHeight() {
        DisplayMetrics dm = Common.getContext().getResources().getDisplayMetrics();
        return dm.heightPixels;
    }

    public static String getMacAddress() {
        String macAddress_1 = MacAddressUtil.getMacAddressGeneral();
        if (TextUtils.isEmpty(macAddress_1) || macIsDefault(macAddress_1)) {
            String macAddress_2 = MacAddressUtil.getMacAddressShell();
            if (!TextUtils.isEmpty(macAddress_2)) {
                return macAddress_2;
            }
        }
        return macAddress_1;
    }

    public static String getNetworkType() {
        if (Common.getContext() == null) {
            return "";
        }

        try {
            NetworkInfo networkInfo = ((ConnectivityManager) Common.getContext().getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
            if (networkInfo == null || !networkInfo.isConnected()) {
                return "";
            }
            if (networkInfo.getType() == 1) {
                return "WIFI";
            }
            if (networkInfo.getType() != 0) {
                return "";
            }
            String _strSubTypeName = networkInfo.getSubtypeName();
            int networkType = networkInfo.getSubtype();
            switch (networkType) {
                case 1:
                case 2:
                case 4:
                case 7:
                case 11:
                    return "2G";
                case 3:
                case 5:
                case 6:
                case 8:
                case 9:
                case 10:
                case 12:
                case 14:
                case 15:
                    return "3G";
                case 13:
                    return "4G";
                default:
                    if (!_strSubTypeName.equalsIgnoreCase("TD-SCDMA") && !_strSubTypeName.equalsIgnoreCase("WCDMA")) {
                        if (!_strSubTypeName.equalsIgnoreCase("CDMA2000")) {
                            return _strSubTypeName;
                        }
                    }
                    return "3G";
            }
        } catch (Exception e) {
            return "";
        }
    }

    public static String getRandomId() {
        return UUID.randomUUID().toString();
    }

    public static String getAndroidId() {
        String androidId = "";
        try {
            androidId = Settings.Secure.getString(Common.getContext().getContentResolver(), Settings.Secure.ANDROID_ID);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return androidId;
    }

    @SuppressLint({"MissingPermission"})
    @Deprecated
    public static String getIMEI() {
        if (!TextUtils.isEmpty(imei)) {
            return imei;
        }
        try {
            if (Build.VERSION.SDK_INT >= 29) {
                imei = getAndroidId();
            } else {
                TelephonyManager tm = (TelephonyManager) Common.getContext().getSystemService(Context.TELEPHONY_SERVICE);
                imei = tm.getDeviceId();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (imei == null) {
            return "";
        }
        return imei;
    }

    public static Map<String, String> getIMEIMap() {
        Map<String, String> map = new HashMap<>();
        String imei1 = getImei1(Common.getContext());
        String imei2 = getImei2(Common.getContext());
        if (!TextUtils.isEmpty(imei1)) {
            map.put(IMEI_1, imei1);
        }
        if (!TextUtils.isEmpty(imei2)) {
            map.put(IMEI_2, imei2);
        }
        return map;
    }

    public static String getIMEI_1() {
        return getImei1(Common.getContext());
    }

    public static String getIMEI_2() {
        return getImei2(Common.getContext());
    }

    @SuppressLint({"MissingPermission"})
    public static String getDeviceId() {
        String androidId = "";
        if (Build.VERSION.SDK_INT >= Q) {
            try {
                androidId = Settings.Secure.getString(Common.getContext().getContentResolver(), Settings.Secure.ANDROID_ID);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            try {
                TelephonyManager tm = (TelephonyManager) Common.getContext().getSystemService(Context.TELEPHONY_SERVICE);
                androidId = tm.getDeviceId();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return androidId;
    }

    public static OperatorEnum getInternetSimOperator() {
        TelephonyManager manager = (TelephonyManager) Common.getContext().getSystemService(Context.TELEPHONY_SERVICE);
        String simOperator = manager.getSimOperator();
        UXLog.i(TAG, "getInternetSimOperator() -> " + simOperator);
        return mccMnc2Operator(simOperator);
    }

    public static OperatorEnum getCallSimOperator() {
        TelephonyManager manager = (TelephonyManager) Common.getContext().getSystemService(Context.TELEPHONY_SERVICE);
        String callOperator = manager.getNetworkOperator();
        UXLog.i(TAG, "getCallSimOperator（） -> " + callOperator);
        return mccMnc2Operator(callOperator);
    }

    private static boolean macIsDefault(@NonNull String macAddr) {
        return TextUtils.equals(MacAddressUtil.MAC_ADDRESS_DEFAULT_1, macAddr) || TextUtils.equals(MacAddressUtil.MAC_ADDRESS_DEFAULT_2, macAddr);
    }

    private static OperatorEnum mccMnc2Operator(String mccMnc) {
        if (TextUtils.equals(mccMnc, "46001") || TextUtils.equals(mccMnc, "46006") || TextUtils.equals(mccMnc, "46009")) {
            return OperatorEnum.Unicom;
        }
        if (TextUtils.equals(mccMnc, "46000") || TextUtils.equals(mccMnc, "46002") || TextUtils.equals(mccMnc, "46004") || TextUtils.equals(mccMnc, "46007")) {
            return OperatorEnum.CMCC;
        }
        if (TextUtils.equals(mccMnc, "46003") || TextUtils.equals(mccMnc, "46005") || TextUtils.equals(mccMnc, "46011")) {
            return OperatorEnum.Telecom;
        }
        if (TextUtils.equals(mccMnc, "中国铁通：46020")) {
            return OperatorEnum.Railcom;
        }
        return OperatorEnum.Unknown;
    }

    @SuppressLint({"MissingPermission"})
    @Deprecated
    public static String getImei1(Context context) {
        if (Build.VERSION.SDK_INT >= 29) {
            DeviceUtil.init(context);
            return DeviceUtil.getAndroidId();
        } else if (Build.VERSION.SDK_INT < 21) {
            String imei = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
            return imei == null ? "" : imei;
        } else {
            try {
                TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
                boolean ret = false;
                if (tm != null) {
                    Method[] declaredMethods = tm.getClass().getDeclaredMethods();
                    int length = declaredMethods.length;
                    for (int i = 0; i < length; i++) {
                        Method m = declaredMethods[i];
                        if (m.getName().equals("getPhoneCount")) {
                            ret = true;
                            break;
                        }
                    }
                }
                if (!ret) {
                    return "";
                }
                Map<String, String> map = getImeiAndMeid(context);
                return map.get("imei1");
            } catch (Exception e) {
                return "";
            }
        }
    }

    @SuppressLint({"NewApi"})
    @Deprecated
    public static String getImei2(Context context) {
        if (Build.VERSION.SDK_INT >= 29) {
            DeviceUtil.init(context);
            return DeviceUtil.getAndroidId();
        } else if (Build.VERSION.SDK_INT < 21) {
            return "";
        } else {
            try {
                TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
                boolean ret = false;
                if (tm != null) {
                    Method[] declaredMethods = tm.getClass().getDeclaredMethods();
                    int length = declaredMethods.length;
                    for (int i = 0; i < length; i++) {
                        Method m = declaredMethods[i];
                        if (m.getName().equals("getPhoneCount")) {
                            ret = true;
                            break;
                        }
                    }
                }
                if (!ret) {
                    return "";
                }
                Map<String, String> map = getImeiAndMeid(context);
                return map.get("imei2");
            } catch (Exception e) {
                return "";
            }
        }
    }

    @SuppressLint({"NewApi", "MissingPermission"})
    @Deprecated
    public static Map getImeiAndMeid(Context ctx) {
        Map<String, String> map = new HashMap<>();
        TelephonyManager mTelephonyManager = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);
        try {
            Class<?> clazz = Class.forName("android.os.SystemProperties");
            Method method = clazz.getMethod("get", String.class, String.class);
            String gsm = (String) method.invoke(null, "ril.gsm.imei", "");
            String meid = (String) method.invoke(null, "ril.cdma.meid", "");
            map.put("meid", meid);
            if (!TextUtils.isEmpty(gsm)) {
                String[] imeiArray = gsm.split(",");
                if (imeiArray != null && imeiArray.length > 0) {
                    map.put("imei1", imeiArray[0]);
                    if (imeiArray.length > 1) {
                        map.put("imei2", imeiArray[1]);
                    } else {
                        map.put("imei2", mTelephonyManager.getDeviceId(1));
                    }
                } else {
                    map.put("imei1", mTelephonyManager.getDeviceId(0));
                    map.put("imei2", mTelephonyManager.getDeviceId(1));
                }
            } else {
                map.put("imei1", mTelephonyManager.getDeviceId(0));
                map.put("imei2", mTelephonyManager.getDeviceId(1));
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return map;
    }

    private static String getMeid(Context context) {
        if (Build.VERSION.SDK_INT >= 29) {
            DeviceUtil.init(context);
            return DeviceUtil.getAndroidId();
        } else if (Build.VERSION.SDK_INT < 21) {
            return "";
        } else {
            try {
                TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
                boolean ret = false;
                if (tm != null) {
                    Method[] declaredMethods = tm.getClass().getDeclaredMethods();
                    int length = declaredMethods.length;
                    for (int i = 0; i < length; i++) {
                        Method m = declaredMethods[i];
                        if (m.getName().equals("getPhoneCount")) {
                            ret = true;
                            break;
                        }
                    }
                }
                if (!ret) {
                    return "";
                }
                Map<String, String> map = getImeiAndMeid(context);
                return map.get("meid");
            } catch (Exception e) {
                return "";
            }
        }
    }

    public enum Type {
        deviceId("deviceId"),
        androidId("androidId"),
        randomId("randomId");

        private String key;
        Type(String key) {
            this.key = key;
        }
        public String getKey() {
            return this.key;
        }
    }

    public enum OperatorEnum {
        Unicom("China Unicom"),
        CMCC("China Mobile"),
        Telecom("China Telecom"),
        Railcom("China Railcom"),
        Unknown("unknown");

        private String key;
        OperatorEnum(String key) {
            this.key = key;
        }
        public String getKey() {
            return this.key;
        }
    }
}
